package com.zyg.async;

import java.util.Random;
import java.util.concurrent.*;

/**
 * 缺陷：
 * 1.执行顺序是按照任务提交顺序执行而并不是通过cpu轮询执行
 * 2.对执行结果的获取需要阻塞，或者抛出超时错误。
 */
public class FutureDemo {

    static ExecutorService executorService = Executors.newFixedThreadPool(100);

    public static void main(String[] args) {
        System.out.println(getArticleScore("文章名称1"));
    }

    /**
     * 并行变串行（任务执行的时间差不同，在调用任务的get时会阻塞等待）
     *
     * @param articleName
     * @return
     */
    public static int getArticleScore(String articleName) {
        //开启异步任务
        Future<Integer> future1 = executorService.submit(new CalculateScore(1));
        Future<Integer> future2 = executorService.submit(new CalculateScore(2));
        Future<Integer> future3 = executorService.submit(new CalculateScore(3));
        doSomeThing();
        int result1 = 0;
        int result2 = 0;
        int result3 = 0;
        try {
            result1 = future1.get();
        } catch (InterruptedException e) {
            future1.cancel(true);
            e.printStackTrace();
        } catch (ExecutionException e) {
            future1.cancel(true);
            e.printStackTrace();
        }
        try {
            result2 = future2.get();
        } catch (InterruptedException e) {
            future2.cancel(true);
            e.printStackTrace();
        } catch (ExecutionException e) {
            future2.cancel(true);
            e.printStackTrace();
        }
        try {
            result3 = future3.get();
        } catch (InterruptedException e) {
            future3.cancel(true);
            e.printStackTrace();
        } catch (ExecutionException e) {
            future3.cancel(true);
            e.printStackTrace();
        }
        executorService.shutdown();
        return result1+result2+result3;

    }

    private static void doSomeThing() {

        System.out.println("main thread execute");
    }

    private static class CalculateScore implements Callable<Integer> {

        private int num;

        public CalculateScore(int num) {
            this.num = num;
        }

        public CalculateScore() {
        }

        @Override
        public Integer call() throws Exception {
            Random random = new Random();
            TimeUnit.SECONDS.sleep(num);
            System.out.println(Thread.currentThread().getName());
            return random.nextInt(100);
        }
    }
}
